<template>
  <div class="page-container">
    <el-card shadow="never">
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">新增角色</el-button>
        <!-- 预留：挂权限按钮 -->
        <el-button type="success" @click="assignPermissions(null)">批量分配权限</el-button>
      </div>

      <!-- 角色表格 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column align="center" prop="name" label="角色名称"/>
        <el-table-column align="center" prop="code" label="角色编码"/>
        <el-table-column align="center" prop="description" label="描述"/>
        <el-table-column align="center" label="操作" width="260">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
            <el-button size="small" type="warning" @click="assignPermissions(row.id)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog :title="form.id ? '编辑角色' : '新增角色'" v-model="showDialog" width="50%">
      <el-form :model="form" label-width="90px" ref="formRef" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="如 ADMIN"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <SelectorDialog
      v-model="selectorVisible"
      :data="allPermissions"
      :selected="selectedPermissionIds"
      title="选择权限"
      label-prop="name"
      key-prop="id"
      @confirm="handleAssignPermissionsConfirm"
  />
</template>

<script setup>
import {onMounted, ref} from 'vue';
import request from '@/api/request';
import {ElMessage, ElMessageBox} from "element-plus";
import SelectorDialog from "@/components/SelectorDialog";

const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

const showDialog = ref(false);
const formRef = ref();
const form = ref({id: null, name: '', code: '', description: ''});

const rules = {
  name: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
  code: [{required: true, message: '请输入角色编码', trigger: 'blur'}]
};

const fetchData = () => {
  loading.value = true;
  request.get('/sys-role/page', {
    params: {page: currentPage.value, size: pageSize.value}
  }).then(res => {
    const data = res.data.data;
    tableData.value = data.records;
    total.value = data.total;
  }).finally(() => {
    loading.value = false;
  });
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

const handleAdd = () => {
  form.value = {id: null, name: '', code: '', description: ''};
  showDialog.value = true;
};

const handleEdit = (row) => {
  form.value = {...row};
  showDialog.value = true;
};

const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该角色吗？', '提示', {type: 'warning'}).then(() => {
    request.delete(`/sys-role/${id}`).then(() => {
      ElMessage.success('删除成功');
      fetchData();
    });
  }).catch(() => {
  });
};

const submitForm = () => {
  formRef.value.validate(valid => {
    if (!valid) return;

    const api = form.value.id ? request.put : request.post;
    api('/sys-role', form.value).then(() => {
      ElMessage.success(form.value.id ? '更新成功' : '添加成功');
      showDialog.value = false;
      fetchData();
    });
  });
};

const selectorVisible = ref(false);
const allPermissions = ref([]);
const selectedPermissionIds = ref([]);
const currentRoleId = ref(null);

// 加载所有权限树
const loadAllPermissions = async () => {
  const res = await request.get('/sys-role-permission/tree/all');
  allPermissions.value = res.data.data || [];
};

// 加载角色已有权限
const loadRolePermissions = async (roleId) => {
  if (!roleId) {
    selectedPermissionIds.value = [];
    return;
  }
  const res = await request.get(`/sys-role-permission/role/${roleId}`);
  selectedPermissionIds.value = res.data.data || [];
};

// 打开分配权限弹窗
const assignPermissions = async (roleId) => {
  const isBatch = roleId === null;
  if (isBatch) {
    ElMessage.warning("暂不支持批量分配权限");
    return;
  }

  await loadAllPermissions();
  await loadRolePermissions(roleId);
  currentRoleId.value = roleId;
  selectorVisible.value = true;
};

// 提交权限分配
const handleAssignPermissionsConfirm = (permissionIds) => {
  const dto = {
    roleId: currentRoleId.value,
    permissionIds
  };

  request.post('/sys-role-permission/assign', dto).then(() => {
    ElMessage.success('权限分配成功');
    fetchData(); // 可刷新角色列表
  }).catch(() => {
  });
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}
</style>
